/*
 *
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution2 {
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode result = l1;
        int flag = 0;

        while (l2 != null) {
            l1.val += l2.val + flag;
            flag = 0;
            if (l1.val >= 10) {
                l1.val -= 10;
                flag = 1;
            }
            l2 = l2.next;
            if (l1.next != null) {
                l1 = l1.next;
            } else if (l2 == null && flag == 1) {
                ListNode p = new ListNode();
                l1.next = p;
                l1 = p;
            } else {
                l1.next = l2;
                l1 = l2;
                break;
            }
        }
        while (flag == 1) {
            l1.val++;
            flag = 0;
            if (l1.val >= 10) {
                l1.val -= 10;
                flag = 1;
                if (l1.next == null) {
                    l1.next = new ListNode();
                }
            }
            l1 = l1.next;
        }
        return result;
    }
}